/**
 * @description: ja简易版，beta阶段，如有问题请联系lync：刘宋健、电话：18134221013
 * @update: 2019-06-14
 * @version: 1.0
 **/
'use strict';

(function () {
    var that;
    var JoinActivity = function () {
        // -----------------全局变量----------------
        this.options = {
            app: undefined,             // 应用 初始化必传项
            activity: undefined,        // 活动 初始化必传项
            version: undefined,         // 版本 初始化必传项
            server: undefined,          // 服务 初始化必传项
            platform: undefined,        // 平台 初始化必传项

            // isWxLogin: false,           // 是否微信授权(暂时关闭)
            // isWxInit: false,            // 微信初始化(暂时关闭)
            // isWxDebug: false,           // 是否开启微信debug调试(暂时关闭)
            host: location.origin,      // 接口请求域名，默认同域名
            isUserInit: false,          // 获取用户信息初始化
            userPlat: 'phone',          // 获取用户信息的平台，默认 phone

            token: undefined,           // token
            cyscid: undefined,          // 地址标识
            isInit: 0,                  // 初始化状态：0 未初始化 ； 1 初始化完成 ； 2 初始化失败
            userInfo: undefined,        // 用户信息
            wechatInfo: undefined,      // 微信用户信息

            ready: function() {},       // 初始化完成后执行
        };
        that = this;
    };
    JoinActivity.fn = JoinActivity.prototype = {
        // -----------------初始化----------------
        config: function(options)   {
            $.extend(this.options, options);
            var _this = this;
            if(this.admin.enable()) {
                _this.user.getToken(function(res) {
                    // 微信是否授权判断授权
                    if(_this.options.isWxLogin) {
                        _this.user.getUserInfo('wechat', function(data) {
                            _this.admin.manage();
                        });
                    }else {
                        _this.admin.manage();
                    }
                })
            }
        },
        // -----------权限(辅助config参数判断)----------------
        admin: {
            enable: function() {
                var isPass = true
                    , arrMust = ['app', 'activity', 'version', 'server', 'platform']
                    , arrWx = ['isWxLogin', 'isWxInit'];
                // 必填项
                arrMust.forEach(function (item, index) {
                    if(!that.options[item]) {
                        alert(item + '为必填项');
                        arrMust = arrMust.concat(arrMust.splice(index, arrMust.length - index));
                        isPass = false;
                    }
                });
                // 微信项为true
                arrWx.forEach(function (item, index) {
                    if(that.options[item] && !that.utils.isWechat()) {
                        alert('初始化失败，需要在微信浏览器中打开');
                        arrWx = arrWx.concat(arrWx.splice(index, arrWx.length - index));
                        isPass = false;
                    }
                });
                return isPass;
            },
            manage: function() {
                // 微信init
                if(that.options.isWxInit) {
                    that.wx.init()
                }
                // 用户init
                if(that.options.isUserInit) {
                    that.user.getUserInfo(that.options.userPlat, that.options.ready);
                }else {
                    that.options.ready();
                }
            },
        },
        // -----------------ajax请求----------------
        client: {
            ajax: function (type, url, data, fun) {
                $.ajax({
                    type: type,
                    url: url,
                    data: data,
                    headers: {
                        'Authorization': that.options.token,
                        'APP': that.options.app,
                        'ACTIVITY': that.options.activity,
                        'VERSIONCODE': that.options.version,
                        'PLAT': that.options.platform,
                        'CYSCID': that.utils.getQueryString('CYSCID') || undefined
                    },
                    success: function(res) {
                        fun(res)
                    }
                })
            },
            baseUrl: function(plat) {
                return that.options.host + '/wb/' + that.options.server + '/' + (plat || that.options.platform);
            },
            get: function(url, data, fun, plat) {
                this.ajax('GET', this.baseUrl(plat) + url, data, fun);
            },
            post: function(url, data, fun, plat) {
                this.ajax('POST', this.baseUrl(plat) + url, data, fun);
            }
        },
        // -----------------用户登陆----------------
        user: {
            url: {
                core: function() { return  '/core/login/' + that.options.app + '/' + that.options.activity + '/' + that.options.version },
                tokenPath: '/init',
                phoneCodePath: '/sendcode',         // 登陆发送手机号验证码
                loginPhonePath: '/phonelogin',      // 手机号登录
                userInfoPath: '/user/info'          // 用户详情
            },
            // 获取token
            getToken: function(fun) {
                that.client.get(this.url.tokenPath, {}, function (res) {
                    if(res.code === 10000) {
                        $.extend(that.options, {
                            token: res.data.token,
                            cyscid: that.utils.getQueryString('CYSCID'),
                            isInit: 1
                        });
                        fun(res);
                    }else {
                        $.extend(that.data, { isInit: 2 });
                        alert(res.message);
                    }
                })
            },
            // 获取验证码
            getCode: function(phone, fun) {
                that.client.post(this.url.phoneCodePath, {
                    phone: phone
                }, function(res) {
                    fun ? fun(res) : alert(res.code === 10000 ? '验证码发送成功' : res.message);
                }, 'phone');
            },
            // 手机号与验证码登陆
            loginPhone: function(phone, code, fun) {
                that.client.post(this.url.core() + this.url.loginPhonePath, {
                    phone: phone,
                    code: code
                }, function(res) {
                    fun ? fun(res) : res.code === 10000 ? location.reload() : alert(res.message);
                }, 'phone');
            },
            // 获取用户信息 --- wechat(微信) changyou(畅游) changyoujia(畅游加) DJ(刀剑) Anonymous(匿名访问) phone(手机) warframe(星际战甲) cyou3(橙柚三联)
            getUserInfo: function(plat, fun) {
                var _user = this;
                that.client.get(this.url.userInfoPath, {}, function(res) {
                    switch (plat) {
                        case 'wechat':
                            if(res.code === 10000) {
                                that.options.wechatInfo = res.data;
                                fun(res);
                            }else {
                                location.href = that.options.host + '/' + that.options.platform + _user.url.core() + '?callback=' + encodeURI(location.href);
                            }
                            break;
                        case 'phone':
                            fun(res);
                            if(res.code === 10000) {
                                that.options.userInfo = res.data;
                            }else {
                                console.log('用户还没有登录');
                            }
                            break;
                    }
                }, plat)
            },
            // 登出
            logout: function (fun) {
                that.client.post(this.url.core() + '/logout', {}, function () {
                    fun || location.reload();
                });
            }
        },
        // -----------------工具类----------------
        utils: {
            // 截取url参数
            getQueryString: function(name) {
                var reg = new RegExp('(^|&)'+ name +'=([^&]*)(&|$)');
                var r = window.location.search.substr(1).match(reg);
                if(r!=null)return  unescape(r[2]); return null;
            },
            // 是否是微信浏览器
            isWechat: function() {
                var ua = window.navigator.userAgent.toLowerCase();
                return ua.match(/MicroMessenger/i) == 'micromessenger'
            },
            // cookie操作
            cookie: {
                get: function(cname) {
                    var name = cname + '=';
                    var ca = document.cookie.split(';');
                    for(var i=0; i<ca.length; i++) {
                        var c = ca[i];
                        while (c.charAt(0)==' ') c = c.substring(1);
                        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
                    }
                    return '';
                },
                set: function(cname, cvalue, exdays) {
                    var d = new Date();
                    d.setTime(d.getTime() + (exdays*24*60*60*1000));
                    var expires = 'expires='+d.toUTCString();
                    document.cookie = cname + '=' + cvalue + '; ' + expires;
                },
                del: function(name) {
                    this.set(name, '', -1);
                }
            }
        },
        // -----------------微信业务----------------
        wx: {
            // 微信初始化
            init: function() {
                $.ajax({
                    url: location.origin + '/wechat/web/' + that.options.activityInfo.wxId + '/config',
                    success: function(data) {
                        if(data.config) {
                            $.getScript('https://res.wx.qq.com/open/js/jweixin-1.4.0.js', function () {
                                wx.config({
                                    debug: that.options.isWxDebug ,     // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                                    appId: data.config.appId,           // 必填，公众号的唯一标识
                                    timestamp: data.config.timestamp,   // 必填，生成签名的时间戳
                                    nonceStr: data.config.nonceStr,     // 必填，生成签名的随机串
                                    signature: data.config.signature,   // 必填，签名，见附录1
                                    jsApiList: [                        // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                                        'onMenuShareTimeline',
                                        'onMenuShareAppMessage',
                                        'onMenuShareQQ',
                                        'onMenuShareWeibo',
                                        'hideMenuItems',
                                        'hideAllNonBaseMenuItem',
                                        'onMenuShareQZone'
                                    ]
                                });
                            })
                        }else {
                            alert('微信初始化失败，' + data.message);
                        }
                    }
                });
            },
            // 分享
            share: function(options) {
                var _options = {
                    type: 'link',
                    shareList: [
                        'onMenuShareTimeline',      // 分享到朋友圈
                        'onMenuShareAppMessage',    // 分享给朋友
                        'onMenuShareQQ',            // 分享到QQ
                        'onMenuShareWeibo',         // 分享到腾讯微博
                        'onMenuShareQZone'          // 分型到QQ空间
                    ]
                };
                _options = $.extend(_options, options);
                var list = _options.shareList;
                delete _options['shareList'];
                wx.ready(function() {
                    for(var i in list) {
                        var shareType = list[i];
                        if($.isFunction(wx[shareType])) {
                            wx[shareType](_options);
                        }
                    }
                })
            }
        }
    };
    window.cyja = new JoinActivity();
}());
